package com.huwaiwai.completablefuture;

import lombok.Data;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

/**
 * Created by hww on 2018/8/28 下午10:27.
 */
@Data
public class Shop {

    private String name;
    private Random random = new Random();

    public Shop(String name) {
        this.name = name;
    }

    public double getPrice(String product) {
        return calculatePrice(product);
    }

    /**
     * 计算价格
     *
     * @param product
     * @return
     */
    private double calculatePrice(String product) {
        delay();
        //数字*字符=数字
        return random.nextDouble()*product.charAt(0)*product.charAt(1);
    }

    /**
     * 模拟耗时操作,阻塞1秒
     */
    private void delay() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * (非阻塞式)异步获取价格
     * @param product
     * @return
     */
    public Future<Double> getPriceAsync(String product){
        //无需等待还没结束的计算,直接返回Future对象
        return CompletableFuture.supplyAsync(() -> calculatePrice(product));
    }
}
